<script setup lang="ts">
import { ref } from 'vue';
import { ChevronDownIcon, MinusCircleIcon } from 'tdesign-icons-vue-next';
import Panel from './Panel.vue';
import ProcessListenerTable from '@/components/flow/ProcessListenerTable.vue';
import { rules } from '@/soar';
import LgUpload from '@/soar/components/LgUpload/index.vue';

const model = ref({});
const visible = ref(false);
defineExpose({
  open(data: any) {
    data.fields ??= [];
    data.buttons ??= [];
    data.listeners ??= [];
    data.titleTemplate ??= '';
    model.value = data;
    visible.value = true;
  },
});

const options = [
  { label: '提交', text: '提交', key: 'submit' },
  { label: '通过', text: '通过', key: 'pass' },
  { label: '驳回', text: '驳回', key: 'reject' },
  { label: '转派', text: '转派', key: 'transfer' },
];

function change(e: any, i: number) {
  const d = options.find((x: any) => x.text === e);
  if (d) {
    model.value.buttons[i].key = d.key;
  }
}

const textareaRef = ref();
function clickDropdown(data: any) {
  // model.value.titleTemplate += `{${data.value}}`;
  const textarea = textareaRef.value;
  if (!textarea) return;
  const textToInsert = `{${data.value}}`;

  // 获取光标位置
  const start = textarea.selectionStart;
  const end = textarea.selectionEnd;

  // 如果没有选中且光标不在（比如 -1），则插入到末尾
  const startPos = start >= 0 ? start : model.value.titleTemplate.length;
  const endPos = end >= 0 ? end : model.value.titleTemplate.length;

  const before = model.value.titleTemplate.substring(0, startPos);
  const after = model.value.titleTemplate.substring(endPos);

  // 更新内容
  model.value.titleTemplate = before + textToInsert + after;

  // 恢复光标位置：放在插入文本之后
  const newCursorPos = startPos + textToInsert.length;

  // 等待 DOM 更新后再设置光标（Vue 3 使用 nextTick）
  requestAnimationFrame(() => {
    textarea.setSelectionRange(newCursorPos, newCursorPos);
    textarea.focus();
  });
}
</script>

<template>
  <panel v-model:visible="visible" width="600px">
    <template #header>流程配置</template>
    <t-form label-align="top" class="gl-h100" :data="model">
      <t-tabs default-value="0" class="gl-h100 gl-tabs-auto-h gl-tabs-space">
        <t-tab-panel label="基本信息" value="0">
          <t-form-item label="logo" name="logo">
            <lg-upload v-model="model.logo" value-type="url" type="img" />
          </t-form-item>
          <t-form-item label="流程编码" name="code" :rules="rules.required('key必填')">
            <t-input v-model="model.code" />
          </t-form-item>
          <t-form-item label="是否禁用" name="disabled">
            <t-switch v-model="model.disabled" />
          </t-form-item>
          <t-form-item label="流程名称" name="name" :rules="rules.required('key必填')">
            <t-input v-model="model.name" />
          </t-form-item>
          <t-form-item name="titleTemplate" :rules="rules.required('key必填')">
            <template #label>
              <span class="gl-mr">流程标题</span>
              <t-dropdown @click="clickDropdown">
                <t-button size="small">
                  插入字段
                  <template #suffix><chevron-down-icon size="16" /></template>
                </t-button>
                <t-dropdown-menu>
                  <t-dropdown-item value="发起人">发起人</t-dropdown-item>
                  <t-dropdown-item value="发起时间">发起时间</t-dropdown-item>
                  <t-dropdown-item value="流程名称">流程名称</t-dropdown-item>
                  <t-dropdown-item v-for="x in model.fields" :key="`form.${x.key}`" :value="`表单·${x.name}`">
                    表单·{{ x.name }}
                  </t-dropdown-item>
                </t-dropdown-menu>
              </t-dropdown>
            </template>
            <t-textarea ref="textareaRef" v-model="model.titleTemplate" />
          </t-form-item>
        </t-tab-panel>
        <t-tab-panel label="字段设置" value="1">
          <table class="gl-table gl-table-0">
            <tr>
              <th class="gl-required">名称</th>
              <th class="gl-required">key</th>
              <th style="width: 80px">
                <t-button @click="model.fields.push({})">添加</t-button>
              </th>
            </tr>
            <tr v-for="(x, i) in model.fields" :key="i">
              <td>
                <t-form-item label-width="0" :name="['fields', i, 'name']" :rules="rules.required('名称必填')">
                  <t-input v-model="x.name" />
                </t-form-item>
              </td>
              <td>
                <t-form-item label-width="0" :name="['fields', i, 'key']" :rules="rules.required('key必填')">
                  <t-input v-model="x.key" />
                </t-form-item>
              </td>
              <td>
                <a class="gl-hover gl-ml" @click="model.fields.splice(i, 1)">
                  <minus-circle-icon style="color: var(--app-color-primary)" size="20" />
                </a>
              </td>
            </tr>
          </table>
        </t-tab-panel>
        <t-tab-panel label="按钮设置" value="2">
          <table class="gl-table gl-table-0">
            <tr>
              <th class="gl-required">名称</th>
              <th class="gl-required">key</th>
              <th style="width: 80px">
                <t-button @click="model.buttons.push({})">添加</t-button>
              </th>
            </tr>
            <tr v-for="(x, i) in model.buttons" :key="i">
              <td>
                <t-form-item label-width="0" :name="['fields', i, 'name']" :rules="rules.required('名称必填')">
                  <t-auto-complete v-model="x.name" :options="options" @change="change($event, i)" />
                </t-form-item>
              </td>
              <td>
                <t-form-item label-width="0" :name="['fields', i, 'key']" :rules="rules.required('key必填')">
                  <t-input v-model="x.key" />
                </t-form-item>
              </td>
              <td>
                <a class="gl-hover gl-ml" @click="model.buttons.splice(i, 1)">
                  <minus-circle-icon style="color: var(--app-color-primary)" size="20" />
                </a>
              </td>
            </tr>
          </table>
        </t-tab-panel>
        <t-tab-panel label="执行监听器" value="3">
          <process-listener-table :data="model.listeners" />
        </t-tab-panel>
      </t-tabs>
    </t-form>
  </panel>
</template>

<style scoped lang="less"></style>
